package com.sh.shanhuo.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.sh.shanhuo.R;
import com.sh.shanhuo.adapter.ItemAdapter;
import com.sh.shanhuo.bean.ContentBean;
import com.sh.shanhuo.bean.LoginBean;
import com.sh.shanhuo.bean.PersonalCenterBean;
import com.sh.shanhuo.database.sort.SortInfoDBUtils;
import com.sh.shanhuo.database.web.WebInfoDBUtils;
import com.sh.shanhuo.dialog.CommonEditDialog;
import com.sh.shanhuo.listener.GsonObjectCallback;
import com.sh.shanhuo.listener.SimpleResultCallback;
import com.sh.shanhuo.utils.OkHttpUtil;
import com.sh.shanhuo.utils.ScreenSwitch;
import com.sh.shanhuo.utils.Tools;
import com.sh.shanhuo.view.CircleImageView;
import com.sh.shanhuo.view.CommonItemDecoration;
import com.tencent.mmkv.MMKV;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class PersonalInfoActivity extends BaseActivity {

    private boolean isLogin;
    private TextView ip;
    private TextView logout;
    private TextView login;
    private TextView nickName;
    private CircleImageView headImage;
    private MMKV mmkv;
    public static LoginBean loginBean;
    private ItemAdapter contentAdapter;
    private final List<ContentBean> contentBeans = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_info;
    }

    @Override
    protected void initView() {
        super.initView();
        mmkv = MMKV.defaultMMKV();
        if (mmkv != null) {
            isLogin = mmkv.decodeBool("isLogin", false);
            if (isLogin) {
                loginBean = MainActivity.loginBean;
            }
        }
        ImageView back = findViewById(R.id.back);
        headImage = findViewById(R.id.headImage);
        ImageView more = findViewById(R.id.more);
        nickName = findViewById(R.id.nickName);
        ip = findViewById(R.id.ip);
        TextView setting = findViewById(R.id.setting);
        TextView feedback = findViewById(R.id.feedback);
        TextView version = findViewById(R.id.version);
        TextView sync = findViewById(R.id.sync);
        logout = findViewById(R.id.logout);
        login = findViewById(R.id.login);
        back.setOnClickListener(this);
        logout.setOnClickListener(this);
        login.setOnClickListener(this);
        more.setOnClickListener(this);
        setting.setOnClickListener(this);
        version.setOnClickListener(this);
        feedback.setOnClickListener(this);
        sync.setOnClickListener(this);
        initItem();
    }

    private void login() {
        MMKV mmkv = MMKV.defaultMMKV();
        String account = "";
        String password = "";
        if (mmkv != null) {
            account = mmkv.decodeString("account");
            password = mmkv.decodeString("password");
        }
        CommonEditDialog.loginDialog(PersonalInfoActivity.this, account, password, new SimpleResultCallback() {
            @Override
            public void onResult(String data1, String data2) {
                loginWithCheck(data1, data2);
            }

            @Override
            public void onButton(String action) {
                if ("forgetPassword".equals(action)) {
                    ScreenSwitch.startActivity(PersonalInfoActivity.this, ForgetPasswordActivity.class,
                            null, ScreenSwitch.RESET_PASSWORD);
                } else if ("gotoRegister".equals(action)) {
                    register();
                }
            }

            @Override
            public void onBean(Object obj) {
                loginBean = (LoginBean) obj;
                MainActivity.loginBean = loginBean;
                isLogin = true;
                ip.setVisibility(View.VISIBLE);
                logout.setVisibility(View.VISIBLE);
                login.setVisibility(View.GONE);
                ip.setText(loginBean.getData().getUserName());
                nickName.setText(loginBean.getData().getNickName());
                Glide.with(PersonalInfoActivity.this)
                        .load(loginBean.getData().getHeadUrl())
                        .placeholder(R.drawable.person_image)
                        .error(R.drawable.person_image).into(headImage);
                setContent();
            }
        });
    }

    private void loginWithCheck(String account, String password) {
        Map<String, String> params = new HashMap<>();
        params.put("userName", account);
        params.put("password", password);
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.LOGIN, params, new GsonObjectCallback<LoginBean>() {
            @Override
            public void onUi(LoginBean bean) {
                if (bean.getCode() == 200 && "操作成功".equals(bean.getMsg())) {
                    MainActivity.loginBean = bean;
                    loginBean = bean;
                    mmkv.encode("isLogin", true);
                    isLogin = true;
                    ip.setVisibility(View.VISIBLE);
                    logout.setVisibility(View.VISIBLE);
                    login.setVisibility(View.GONE);
                    ip.setText(bean.getData().getUserName());
                    nickName.setText(bean.getData().getNickName());
                    Glide.with(PersonalInfoActivity.this)
                            .load(bean.getData().getHeadUrl())
                            .placeholder(R.drawable.person_image)
                            .error(R.drawable.person_image).into(headImage);
                    setContent();
                } else {
                    Toast.makeText(PersonalInfoActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    mmkv.encode("isLogin", false);
                }
            }

            @Override
            public void onFailed(Call call, IOException e) {
                onDismissLoading();
                Toast.makeText(PersonalInfoActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                mmkv.encode("isLogin", false);
            }
        });
    }

    private void register() {
        CommonEditDialog.registerDialog(PersonalInfoActivity.this, new SimpleResultCallback() {
            @Override
            public void onResult(String data1, String data2) {
                Bundle bundle = new Bundle();
                bundle.putString("account", data1);
                bundle.putString("password", data2);
                ScreenSwitch.startActivity(PersonalInfoActivity.this, AddPersonalInfoActivity.class, bundle, ScreenSwitch.REGISTER_SUCCESS);
            }

            @Override
            public void onButton(String action) {
                if ("gotoLogin".equals(action)) {
                    login();
                }
            }

            @Override
            public void onBean(Object obj) {

            }
        });
    }

    private void initItem() {
        RecyclerView itemRecyclerView = findViewById(R.id.itemRecyclerView);
        itemRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        itemRecyclerView.addItemDecoration(new CommonItemDecoration(Tools.dp2px(mContext, 15),
                Tools.dp2px(mContext, 15), Tools.dp2px(mContext, 15)));
        contentAdapter = new ItemAdapter(this, null);
        itemRecyclerView.setAdapter(contentAdapter);
        contentAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (!isLogin) {
                login();
                return;
            }
            Bundle bundle = new Bundle();
            if (position == 0) {
                bundle.putString("userName", loginBean.getData().getUserName());
                ScreenSwitch.startActivity(PersonalInfoActivity.this,
                        NoticeActivity.class, bundle);
            } else {
                String url = contentBeans.get(position).getRemark();
                if (TextUtils.isEmpty(url)) {
                    return;
                }
                bundle.putString("url", contentBeans.get(position).getRemark());
                bundle.putString("id", contentBeans.get(position).getId());
                ScreenSwitch.startActivity(PersonalInfoActivity.this,
                        WebActivity.class, bundle);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isLogin) {
            nickName.setText("未登录");
            ip.setVisibility(View.GONE);
            logout.setVisibility(View.GONE);
            login.setVisibility(View.VISIBLE);
        } else {
            loginWithCheck(loginBean.getData().getUserName(), loginBean.getData().getPassword());
        }
        setContent();
    }

    private void setContent() {
        contentBeans.clear();
        if (isLogin) {
            getPersonalCenter(loginBean.getData().getUserName());
        } else {
            getPersonalCenter("");
        }
    }

    private void getPersonalCenter(String userName) {
        Map<String, String> params = new HashMap<>();
        if (isLogin) {
            onShowLoading();
            params.put("userName", userName);
        } else {
            contentBeans.clear();
            contentBeans.add(new ContentBean());
            contentBeans.add(new ContentBean());
            contentBeans.add(new ContentBean());
            contentAdapter.setNewData(contentBeans);
            return;
        }
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.PERSONAL_CENTER_LIST, params, new GsonObjectCallback<PersonalCenterBean>() {
            @Override
            public void onUi(PersonalCenterBean personalCenterBean) {
                contentBeans.clear();
                ContentBean contentBean0 = new ContentBean();
                contentBean0.setContent("通知");
                contentBeans.add(contentBean0);
                if (personalCenterBean.getCode() == 200 && personalCenterBean.getMsg().equals("操作成功")) {
                    contentBean0.setNum(personalCenterBean.getData().getNumber() + "");
                    for (PersonalCenterBean.DataBean.ListBean listBean : personalCenterBean.getData().getList()) {
                        ContentBean contentBean = new ContentBean();
                        contentBean.setContent(listBean.getName());
                        contentBean.setId(listBean.getId() + "");
                        contentBean.setUrl(listBean.getLogoUrl());
                        contentBean.setRemark(listBean.getRemark());
                        contentBeans.add(contentBean);
                    }
                } else {
                    contentBeans.add(new ContentBean());
                    contentBeans.add(new ContentBean());
                }
                contentAdapter.setNewData(contentBeans);
                onDismissLoading();
            }

            @Override
            public void onFailed(Call call, IOException e) {
                contentBeans.add(new ContentBean());
                contentBeans.add(new ContentBean());
                contentBeans.add(new ContentBean());
                contentAdapter.setNewData(contentBeans);
                onDismissLoading();
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        int id = v.getId();
        Bundle bundle = new Bundle();
        switch (id) {
            case R.id.back:
                finish();
                break;
            case R.id.logout:
                CommonEditDialog.syncDialog(PersonalInfoActivity.this, new SimpleResultCallback() {
                    @Override
                    public void onResult(String data1, String data2) {

                    }

                    @Override
                    public void onButton(String action) {
                        if ("sync".equals(action)) {
                            bundle.putString("appUserName", loginBean.getData().getUserName());
                            ScreenSwitch.startActivity(PersonalInfoActivity.this,
                                    CloudActivity.class, null);
                        }
                        if ("exit".equals(action)) {
                            WebInfoDBUtils.deleteAll(PersonalInfoActivity.this);
                            SortInfoDBUtils.deleteAll(PersonalInfoActivity.this);
                            isLogin = false;
                            mmkv.encode("isLogin", false);
                            nickName.setText("未登录");
                            ip.setVisibility(View.GONE);
                            logout.setVisibility(View.GONE);
                            login.setVisibility(View.VISIBLE);
                            Glide.with(PersonalInfoActivity.this).load(R.drawable.person_image).into(headImage);
                            setContent();
                        }
                    }

                    @Override
                    public void onBean(Object obj) {

                    }
                });
                break;
            case R.id.more:
            case R.id.login:
                if (isLogin) {
                    ScreenSwitch.startActivity(PersonalInfoActivity.this, PersonalMoreActivity.class, null);
                } else {
                    login();
                }
                break;
            case R.id.setting:
                if (isLogin) {
                    ScreenSwitch.startActivity(PersonalInfoActivity.this,
                            SettingActivity.class, null);
                } else {
                    login();
                }
                break;
            case R.id.version:
                ScreenSwitch.startActivity(PersonalInfoActivity.this,
                        VersionActivity.class, null);
                break;
            case R.id.feedback:
                if (isLogin) {
                    bundle.putString("appUserName", loginBean.getData().getUserName());
                    bundle.putString("appUserId", loginBean.getData().getId() + "");
                    bundle.putString("appNickName", loginBean.getData().getNickName());
                }
                ScreenSwitch.startActivity(PersonalInfoActivity.this,
                        FeedbackActivity.class, bundle);
                break;
            case R.id.sync:
                if (isLogin) {
                    bundle.putString("appUserName", loginBean.getData().getUserName());
                    ScreenSwitch.startActivity(PersonalInfoActivity.this,
                            CloudActivity.class, bundle);
                } else {
                    login();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ScreenSwitch.REGISTER_SUCCESS || requestCode == ScreenSwitch.RESET_PASSWORD) {
            login();
        }
    }
}